package com.tungse.dynamic.cfg;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(1) // 确保在事务切面之前执行
public class DataSourceAspect {

    /**
     * 配置读方法切点（匹配 select, find, get 开头的方法）
     */
    @Pointcut("execution(* com.tungse.dynamic.service..*.select*(..)) || " +
             "execution(* com.tungse.dynamic.service..*.find*(..)) || " +
             "execution(* com.tungse.dynamic.service..*.get*(..))")
    public void readPointcut() {}

    /**
     * 配置写方法切点（匹配 insert, update, delete, save 开头的方法）
     */
    @Pointcut("execution(* com.tungse.dynamic.service..*.insert*(..)) || " +
             "execution(* com.tungse.dynamic.service..*.update*(..)) || " +
             "execution(* com.tungse.dynamic.service..*.delete*(..)) || " +
             "execution(* com.tungse.dynamic.service..*.save*(..))")
    public void writePointcut() {}

    @Before("readPointcut()")
    public void beforeRead() {
        System.out.println("切换到从库数据源");
        DataSourceContextHolder.setDataSourceType(DataSourceType.SLAVE);
    }

    @Before("writePointcut()")
    public void beforeWrite() {
        System.out.println("切换到主库数据源");
        DataSourceContextHolder.setDataSourceType(DataSourceType.MASTER);
    }

    @After("readPointcut() || writePointcut()") // 方法执行完毕后清理上下文
    public void afterMethod() {
        System.out.println("DataSourceContextHolder.getDataSourceType() = " + DataSourceContextHolder.getDataSourceType());
        DataSourceContextHolder.clear();
    }
}